package com.example.onlinetaxi.ui.activity.HomePage;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.example.onlinetaxi.R;
import com.example.onlinetaxi.callback.HomeCallBack.IRegisterToLogin;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.phoneUtil.PhoneUtil;
import com.example.onlinetaxi.view.VerifyCodeButton;

import java.util.HashMap;
import java.util.Map;

public class RegisterFragment extends Fragment {

    private View rootView;
    // register页面定义的组件
    private EditText phoneET;
    private EditText verifyCodeET;
    private EditText passwordET;
    private EditText repasswordET;
    private Button registerBtn;
    // 引入验证码按钮
    private VerifyCodeButton verifyCodeButton;
    // 用户输入
    private String phoneStr;
    private String verifyCodeStr;
    private String passwordStr;
    private String repasswordStr;

    private IRegisterToLogin iRegisterToLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // 确保只赋值一次
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_register, container, false);
        }

        // 初始化控件
        initView();
        // 为控件添加事件
        initEvent();

        return rootView;
    }

    private boolean sendRegisterRequest() {
        // 组织表单数据
        Map<String, String> map = new HashMap<>();
        map.put("phone", phoneStr);
        map.put("password", passwordStr);
        map.put("verifyCode", verifyCodeStr);
        map.put("type", "passenger");


        // 向后端发起注册请求
        String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "register", "doRegister");
        DataResponse dataResponse = GetDataResponse.getDataResponse(response);
        // 从返回数据中取出请求是否成功的参数
        if (dataResponse.getCode().equals("200")){
            // 操作成功
            Toast.makeText(getActivity(),
                    GetDataResponse.getDataResponse(response).getData().get("success").toString(),
                    Toast.LENGTH_SHORT).show();
        }else{
            //操作失败
            Toast.makeText(getActivity(),
                    GetDataResponse.getDataResponse(response).getData().get("error").toString(),
                    Toast.LENGTH_SHORT).show();
        }

        return true;
    }

    private boolean isCorrect() {
        // 获取用户输入
        phoneStr = phoneET.getText().toString();
        verifyCodeStr = verifyCodeET.getText().toString();
        passwordStr = passwordET.getText().toString();
        repasswordStr = repasswordET.getText().toString();

        // 判断用户注册输入内容是否合理
        if (!PhoneUtil.isMobileNO(phoneStr)) {
            Toast.makeText(getActivity(), "手机号格式错误！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (verifyCodeStr.equals("") || verifyCodeStr == null) {
            Toast.makeText(getActivity(), "验证码不能为空！！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (passwordStr.equals("") || passwordStr == null) {
            Toast.makeText(getActivity(), "密码不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (repasswordStr.equals("") || repasswordStr == null) {
            Toast.makeText(getActivity(), "重复密码不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        } else if (!passwordStr.equals(repasswordStr)) {
            Toast.makeText(getActivity(), "两次输入的密码不一致！", Toast.LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    public void setIRegisterToLogin(IRegisterToLogin iRegisterToLogin) {
        this.iRegisterToLogin = iRegisterToLogin;
    }

    private void initEvent() {
        // 注册按钮
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 对用户输入进行验证
                if (isCorrect()) {
                    // 通过验证
                    // 向后端发起注册请求
                    if (sendRegisterRequest()) {
                        // 提示用户注册成功
                        Toast.makeText(getActivity(), "注册成功！", Toast.LENGTH_SHORT).show();
                        // 进行fragment跳转
                        iRegisterToLogin.toLoginPage();
                        // 清除当前页面用户输入的所有内容
                        phoneET.setText("");
                        verifyCodeET.setText("");
                        passwordET.setText("");
                        repasswordET.setText("");

                    } else {
                        // 请求发起失败
                        Toast.makeText(getActivity(), "注册请求失败，请联系管理员进行处理！", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        // 获取验证码按钮
        verifyCodeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取手机号
                phoneStr = phoneET.getText().toString();

                // 判断phone的值是否合适
                boolean isPhone = PhoneUtil.isMobileNO(phoneStr);
                if (!isPhone) {
                    // 手机号错误
                    Toast.makeText(getActivity(), "手机号格式错误！", Toast.LENGTH_SHORT).show();
                } else {
                    // 提示用户发送成功
                    Toast.makeText(getActivity(), "短信验证码已发送！", Toast.LENGTH_SHORT).show();
                    // 设置验证码输入框获取焦点
                    verifyCodeET.setFocusable(true);
                    verifyCodeET.requestFocus();

                    // 按钮不可再点击
                    verifyCodeButton.start();

                    // 核心：设置向后台提交的参数
                    Map<String, String> map = new HashMap<>();
                    map.put("phone", phoneStr);
                    // 发送post异步请求
                    String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "SMS", "registerMessage");
                    // 接收响应体
                    DataResponse dataResponse = GetDataResponse.getDataResponse(response);
                    if(dataResponse.getCode().equals("200")){
                        // 请求发送成功
                        Log.e("validate-code", dataResponse.getData().get("validate-code").toString());
                    }else{
                        Toast.makeText(getActivity(), dataResponse.getData().get("error").toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    private void initView() {
        // 初始化其他控件
        phoneET = rootView.findViewById(R.id.register_et_phone);
        verifyCodeET = rootView.findViewById(R.id.register_et_verifyCode);
        passwordET = rootView.findViewById(R.id.register_et_password);
        repasswordET = rootView.findViewById(R.id.register_et_repassword);

        // 获取交换控件
        registerBtn = rootView.findViewById(R.id.register_btn);
        // 初始化验证码发送按钮
        verifyCodeButton = rootView.findViewById(R.id.register_btn_verifyCode);
    }
}